<?php
/**
 * 在用户中心内，用户给自己给手机发短信
 */

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
require_once ROOT_PATH . 'sms_emay/sms_emay.php';

//定义一些常量
$max_sms_times = 5;	//一个虚拟商品最多可发短信次数

$user_id = $_SESSION['user_id'];
if($user_id<=0){
	return false;
}

$cid = $_POST['cid'];
$mobile = $_POST['mobile'];
$order_sn = $_POST['order'];
$msg = $_POST['msg'];

//发短信
echo send_msg($user_id, $order_sn, $mobile, $msg, $cid, $max_sms_times);
exit;

/**
 * 在用户中心内，用户给自己给手机发短信(1:表示发送成功,2:已发送次数达到最大限度的5次)
 * 
 * @param int $user_id
 * @param string $order_sn
 * @param $mobile
 * @param string $message
 */
function send_msg($user_id=0, $order_sn='', $mobile='', $msg='', $cid=0, $max_sms_times=5)
{
	if( empty($user_id) || empty($order_sn) || empty($mobile) || empty($msg) || empty($cid))
	{
		return false;	
	}
	
	//判断发送短信的定单是否合法，如果没有找到相关记录，说明在作弊
	$sql_ck = "SELECT count(*) FROM " . $GLOBALS['ecs']->table('order_info') . " WHERE user_id={$user_id} AND order_sn={$order_sn}";
	$count = $GLOBALS['db']->getOne($sql_ck);
	if($count==0)
	{
		return false;
	}
	
	$sql = "SELECT times FROM " . $GLOBALS['ecs']->table('order_sms') . " WHERE user_id = {$user_id} AND order_sn='{$order_sn}' AND card_id={$cid}";
	$row = $GLOBALS['db']->getRow($sql);
//	print_r($sql);exit;
	if( empty($row['times']) )
	{
		//给手机发短信，如果发成功才记录到数据库
		$message = "定单号{$order_sn},{$msg}";
		$message = iconv("UTF-8", "GBK", $message);
		$smsObj = new SmsEmay($GLOBALS['cfg']['sms']['gw_url'], $GLOBALS['cfg']['sms']['serial'], $GLOBALS['cfg']['sms']['passwd'], $GLOBALS['cfg']['sms']['key']);
		$rs = $smsObj->send_msg(array($mobile), $message);
		//$rs = true;
		if($rs == true)
		{
			//首次发送，需插入一条
			$time = time();
			$sql_insert = "INSERT INTO " . $GLOBALS['ecs']->table('order_sms') . "(order_sn,user_id,card_id,times,created)";
			$sql_insert .= " VALUES({$order_sn},'{$user_id}',{$cid},1,{$time})";
			if( $GLOBALS['db']->query($sql_insert) )
			{
				return 1;
			}
			else
			{
				return 0;
			}
		}
		else
		{
			return 0;
		}
	}
	elseif ( !empty($row['times']) && $row['times']<$max_sms_times )
	{
		$message = "定单号{$order_sn},{$msg}";
		$message = iconv("UTF-8", "GBK", $message);
		$smsObj = new SmsEmay($GLOBALS['cfg']['sms']['gw_url'], $GLOBALS['cfg']['sms']['serial'], $GLOBALS['cfg']['sms']['passwd'], $GLOBALS['cfg']['sms']['key']);
		$rs = $smsObj->send_msg(array($mobile),$message);
		//$rs = true;
		if ($rs == true)
		{
			$sql_update = "UPDATE " . $GLOBALS['ecs']->table('order_sms') . " SET times=times+1 WHERE user_id={$user_id} AND order_sn='{$order_sn}' AND card_id={$cid}";
			if( $GLOBALS['db']->query($sql_update) )
			{
				return 1;
			}
			else
			{
				return 0;
			}
		}
		else
		{
			return 0;
		}
	}
	elseif ($row['times']==$max_sms_times)
	{
		//最多发送5次
		return 2;
	}
	else
	{
		return 0;
	}
}

?>